// import axios from 'axios'
import { webContents } from '@electron/remote'
import { capture } from './capture'
import EventEmitter from 'eventemitter3'

export interface IBrowserContentConfig {
    webviewDom: Electron.WebviewTag
    webviewDevtoolsDom: Electron.WebviewTag
    initialUrl?: string
}

export type IWebviewContentEvent = 'background-image-selected' | 'response-received'

export class WebviewContent extends EventEmitter<IWebviewContentEvent> {
    inited = false
    visible = true
    config: IBrowserContentConfig | null = null
    // webview
    webviewIsVisible = true
    webviewParentElement: HTMLElement | null = null
    webview: Electron.WebviewTag | null = null
    webviewWebContent: Electron.WebContents | null = null
    // webviewDevtools
    webviewDevtoolsIsVisible = true
    webviewDevtoolsParentElement: HTMLElement | null = null
    webviewDevtools: Electron.WebviewTag | null = null
    webviewDevtoolsWebContent: Electron.WebContents | null = null
    // 是否是移动端
    isMobile = false
    // 实例集合
    static instances: WebviewContent[] = []

    constructor() {
        super()
        WebviewContent.instances.push(this)
    }

    // 从webviewDom获取webContents
    getWebContent(dom: Electron.WebviewTag) {
        const id = dom.getWebContentsId()
        return webContents.fromId(id) || null
    }

    // 尺寸改变
    handleContainerResize = () => {
        if (this.webview && this.webviewParentElement) {
            const { x, y, width, height } = this.webviewParentElement.getBoundingClientRect()
            if (width && height) {
                this.webview.style.position = 'fixed'
                this.webview.style.left = `${x}px`
                this.webview.style.top = `${y}px`
                this.webview.style.width = `${width}px`
                this.webview.style.height = `${height}px`
            }
        }
        if (this.webviewDevtools && this.webviewDevtoolsParentElement) {
            const { x, y, width, height } = this.webviewDevtoolsParentElement.getBoundingClientRect()
            if (width && height) {
                this.webviewDevtools.style.position = 'fixed'
                this.webviewDevtools.style.left = `${x}px`
                this.webviewDevtools.style.top = `${y}px`
                this.webviewDevtools.style.width = `${width}px`
                this.webviewDevtools.style.height = `${height}px`
            }
        }
    }

    // console-message
    handleConsoleMessage = (e: Electron.ConsoleMessageEvent) => {
        // console.log('console-message')
        if (e.message.startsWith('BACKGROUND_IMAGE ')) {
            const message = e.message.replace('BACKGROUND_IMAGE ', '')
            this.emit('background-image-selected', message)
            // config?.onBackgroundImageSelected && config?.onBackgroundImageSelected(message)
        }
    }

    // 初始化
    async initBrowserContent(config: IBrowserContentConfig) {
        if (this.inited) return
        this.config = config
        this.inited = true
        // 保存dom
        this.webview = config.webviewDom
        this.webviewDevtools = config.webviewDevtoolsDom
        // 开始处理

        // 保存parent，挂在到body中
        this.webviewParentElement = this.webview.parentElement
        this.webviewDevtoolsParentElement = this.webviewDevtools.parentElement
        document.body.appendChild(this.webview)
        document.body.appendChild(this.webviewDevtools)
        // 窗口尺寸变化的时候
        window.addEventListener('resize', this.handleContainerResize)
        this.handleContainerResize()

        const proms: Promise<void>[] = []
        // 两个webview内容加载完成后吧webContents对象保存起来
        const webviewProm = new Promise<void>((resolve) => {
            this.webview!.addEventListener('dom-ready', () => {
                // console.log('dom-ready')
                this.webviewWebContent = this.getWebContent(this.webview!)
                resolve()
            })
        })
        const devtoolsProm = new Promise<void>((resolve) => {
            this.webviewDevtools!.addEventListener('dom-ready', () => {
                // console.log('dom-ready')
                this.webviewDevtoolsWebContent = this.getWebContent(this.webviewDevtools!)
                resolve()
            })
        })
        proms.push(webviewProm)
        proms.push(devtoolsProm)

        // 两个webview都准备好
        await Promise.all(proms)
        // if (!webContent.devtools || !webContent.webview) return
        if (!this.webviewWebContent || !this.webviewDevtoolsWebContent) return
        this.handleContainerResize()
        // devtools显示在右边的webview里面
        this.webviewWebContent.setDevToolsWebContents(this.webviewDevtoolsWebContent)

        // 默认打开devtools start
        // this.webviewWebContent.openDevTools({ mode: 'undocked' })
        // this.webviewDevtoolsWebContent.executeJavaScript('window.location.reload()')
        // 默认打开devtools end

        // 挂载debugger，1. 要捕获响应，2. 要启用touch模式
        this.webviewWebContent.debugger.attach('1.3')

        // 捕获蓝湖的响应
        capture(this.webviewWebContent, this)

        // 每次发生加载完成事件后往window里注入onSelectionChanged监听器，选中元素变化时触发
        this.webview.addEventListener('did-finish-load', () => {
            // console.log('webview did-finish-load')
            // 声明onSelectionChanged函数，此函数会被devtools插件在选中元素时调用
            this.webviewWebContent?.executeJavaScript(`
window.onSelectionChanged = () => {
    const el = $0
    const backgroundImage = getComputedStyle(el).backgroundImage
    let src = backgroundImage
    // 是img元素吗
    console.log(el.src)
    if (el.tagName === 'IMG') {
            src = el.src
    }
    console.log('BACKGROUND_IMAGE ' + src)
}
        `)
        })

        // 监听webview的console消息
        this.webview.addEventListener('console-message', this.handleConsoleMessage)
    }

    // 获取webContentsView
    getWebContentsView() {
        return this.webviewWebContent
    }

    // 加载路径
    loadUrl(url: string) {
        this.webviewWebContent?.loadURL(url)
    }

    // 设置成touch模式
    toggleTouchMode(enabled: boolean) {
        if (!this.webviewWebContent) return
        this.webviewWebContent.debugger.sendCommand('Emulation.setTouchEmulationEnabled', {
            enabled,
            configuration: 'mobile'
        })
        this.webviewWebContent.debugger.sendCommand('Emulation.setEmitTouchEventsForMouse', { enabled })
    }

    // 开启移动端模拟
    toggleMobileMode(enabled: boolean, _params?: Electron.Parameters) {
        this.isMobile = enabled
        if (!enabled) {
            this.webviewWebContent?.disableDeviceEmulation()
            return
        }
        this.webviewWebContent?.enableDeviceEmulation({
            screenPosition: 'mobile',
            screenSize: { width: 0, height: 0 },
            viewPosition: { x: 0, y: 0 },
            deviceScaleFactor: 2,
            viewSize: { width: 0, height: 0 },
            scale: 1
        })
    }

    // 开启或关闭devtoolse
    toggleDevtools(visible: boolean) {
        if (visible) {
            this.webviewWebContent?.openDevTools({ mode: 'undocked' })
            this.webviewDevtoolsWebContent?.executeJavaScript('window.location.reload()')
        } else {
            this.webviewWebContent?.closeDevTools()
        }
        this.setVisible(visible, 'devtools')
        setTimeout(() => {
            this.handleContainerResize()
        }, 300)
    }

    // 设置可见性
    setVisible(visible: boolean, only?: 'webview' | 'devtools') {
        const display = visible ? '' : 'none'
        if (this.webview && only !== 'devtools') {
            this.webviewIsVisible = visible
            this.webview.style.display = display
        }
        if (this.webviewDevtools && only !== 'webview') {
            this.webviewDevtoolsIsVisible = visible
            this.webviewDevtools.style.display = display
        }
    }

    // 销毁
    destroy() {
        this.webview?.remove()
        this.webviewDevtools?.remove()
        window.removeEventListener('resize', this.handleContainerResize)
        const index = WebviewContent.instances.indexOf(this)
        if (index !== -1) {
            WebviewContent.instances.splice(index, 1)
        }
    }
}

// @ts-ignore
window.WebviewContent = WebviewContent
